package com.wang.wemedia.interceptor;

import com.wang.util.WmThreadLocalUtil;
import com.wang.wemedia.api.model.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置请求拦截后的处理
 * 这里主要获取UserId
 *
 * @author: wangning
 * @date: 2024/1/11 15:40
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    /**
     * 请求前触发方法，存入userId
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            WmUser user = new WmUser();
            user.setId(Integer.valueOf(userId));
            WmThreadLocalUtil.setUser(user);
            log.info("存储user到ThreadLocal中...");
        }
        return true;
    }

    /**
     * 请求后触发方法，清理userId
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.clear();
        log.info("清理ThreadLocal...");
    }
}
